from flask import Blueprint, render_template, request, redirect, url_for
from flask_login_multi import login_user, logout_user, login_required

from forms.front import RegisterForm, LoginForm
from models.base import db
from models.category import Category
from models.user import User
from utils import restful

front = Blueprint('front', __name__)


@front.route('/')
def hello_world():
    cates = Category.query.all()
    return render_template('home.html', cates=cates)


@front.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'GET':
        return render_template('login.html')
    form = LoginForm(request.form)
    if form.validate():
        username = form.username.data
        user = User.query.filter_by(username=username).first()
        if not (user and user.check_password(form.password.data)):
            return restful.param_error('用户不存在或密码错误')
        login_user(user)
        return restful.success()
    else:
        return restful.form_error(form)


@front.route('/logout', methods=['GET', 'POST'])
def logout():
    logout_user()
    return redirect(url_for('front.login'))


@front.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'GET':
        return render_template('register.html')
    form = RegisterForm(request.form)
    if form.validate():
        with db.auto_commit():
            user = User()
            user.username = form.username.data
            user.password = form.password.data
            db.session.add(user)
        return restful.success()
    else:
        return restful.form_error(form)
